package service

import (
	"encoding/json"
	"fmt"
	ClickHouse "gin/database"
	"gin/types"
	"github.com/gin-gonic/gin"
	teamones_helper "github.com/teamones-open/go-helper"
	"time"
)

type WorkHour struct {
}

// QueryUserWorkHour 查询用户上班打卡工时
func (w WorkHour) QueryUserWorkHour(UserIdList []uint64, startDate, endDate string, ctx *gin.Context) (res map[uint64]float64, err error) {
	var tr TeamonesRequest
	var req = types.QueryUserWorkHourByDateReq{
		UserIdList:    UserIdList,
		WorkDateStart: startDate,
		WorkDateEnd:   endDate,
	}
	reqStr, _ := json.Marshal(req)
	rk := fmt.Sprintf("teamones-work-hour:dingtalk_get_user_work_times:%s", teamones_helper.GenerateMd5(string(reqStr)))
	val, _ := ClickHouse.Rdb.Get(rk).Result()
	if val != "" {
		err = json.Unmarshal([]byte(val), &res)
		if err == nil {
			return
		}
	}

	var headers = map[string]string{"x-userinfo": GetStringFromContext(ctx, "x-userinfo")}
	var resList types.QueryUserWorkHourByDateResItem
	err = tr.Do("teamones-work-hour", "dingtalk/get_user_work_times", req, headers, &resList)
	if err != nil {
		return
	}
	res = make(map[uint64]float64, 0)
	for _, item := range resList.Data {
		res[item.UserId] = item.WorkHour
	}

	rs, err := json.Marshal(res)
	if err != nil {
		return
	}
	_, err = ClickHouse.Rdb.Set(rk, rs, time.Minute*3).Result()
	if err != nil {
		return
	}
	return
}

// QueryUserWorkHourTotal 查询用户上班打卡工时汇总
func (w WorkHour) QueryUserWorkHourTotal(UserIdList []uint64, startDate, endDate string, ctx *gin.Context) (res int64, err error) {
	var tr TeamonesRequest
	var req = types.QueryUserWorkHourByDateReq{
		UserIdList:    UserIdList,
		WorkDateStart: startDate,
		WorkDateEnd:   endDate,
	}
	reqStr, _ := json.Marshal(req)
	rk := fmt.Sprintf("teamones-work-hour:dingtalk_get_user_work_time_total:%s", teamones_helper.GenerateMd5(string(reqStr)))
	val, _ := ClickHouse.Rdb.Get(rk).Result()
	if val != "" {
		err = json.Unmarshal([]byte(val), &res)
		if err == nil {
			return
		}
	}
	var headers = map[string]string{"x-userinfo": GetStringFromContext(ctx, "x-userinfo")}
	var resList types.GetUserWorkTimeTotalRes
	err = tr.Do("teamones-work-hour", "dingtalk/get_user_work_time_total", req, headers, &resList)
	if err != nil {
		return
	}
	res = resList.Data
	rs, err := json.Marshal(res)
	if err != nil {
		return
	}
	_, err = ClickHouse.Rdb.Set(rk, rs, time.Minute*3).Result()
	if err != nil {
		return
	}
	return resList.Data, nil
}
